package org.visionlibrary.image.filters.effects;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class Mixing extends AbstractFilter {
	private TiledImage src1;

	private float alpha;

	public Mixing(TiledImage src1, float alpha) {
		if (alpha < 0.0 || alpha > 1.0)
			throw new IllegalArgumentException(
					"Alpha is out of range, use value in 0.0f .. 1.0f.");
		this.src1 = src1;
		this.alpha = alpha;
	}

	public TiledImage applyFilter(TiledImage src2, TiledImage dest) {
		if (null == src2)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src2);
		
		//TODO sprawdzac czy zgadza sie colormodel lub colorspace zamiast ilosc kanalow!!
		if (src1.getWidth() != src2.getWidth()
				|| src1.getHeight() != src2.getHeight()
				|| src1.getNumBands() != src2.getNumBands())
			throw new IllegalArgumentException(
					"Cannot mix images of different sizes or types");

		int maxX = src1.getWidth();
		int maxY = src1.getHeight();
		for (int ch = 0; ch < src1.getNumBands(); ch++)
			for (int x = 0; x < maxX; x++)
				for (int y = 0; y < maxY; y++) {
					int value = (int) ((alpha
							* (float) src1.getSample(x, y, ch) + (1.0 - alpha)
							* (float) src2.getSample(x, y, ch)));
					dest.setSample(x, y, ch, value);
				}
		return dest;
	}
}
